package com.chenshu.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-04-24
 * Time：10:31
 */
public class StringToDateConverter implements Converter<String, Date> {
    private String datePattern;

    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }

    @Override
    public Date convert(String s) {
        if (!StringUtils.hasLength(s)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
        Date result = null;
        try {
            result = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println(e.getMessage() + ": 日期格式转换失败。");
        }
        return result;
    }
}
